package lgvalle.com.fluxtodo.flux.fluxbase;


import de.greenrobot.event.EventBus;

//import javax.inject.Inject;

/**
 * Created by lgvalle on 19/07/15.
 */
public class Dispatcher {
    // 事件总线
    private final EventBus bus;
    // 构造方法 时间总线 依赖注入
    //@Inject
    public Dispatcher(EventBus bus) {
        this.bus = bus;
    }

    public void register(final Object cls) {
        bus.register(cls);
    }

    // 事件总线注销注册
    public void unregister(final Object obj) {
        bus.unregister(obj);
    }

    // 通知ui 有更新了
    public void notifyStoreChangedToUI(Store.StoreChangeEvent event) {
        postToBus(event);
    }

    // 分发action
    public void dispatch(String type, Object... data) {
        if (isEmpty(type)) {
            throw new IllegalArgumentException("Type must not be empty");
        }

        if (data.length % 2 != 0) {
            throw new IllegalArgumentException("Data must be a valid list of key,value pairs");
        }

        // 通过type 和datas 构造action
        Action.Builder actionBuilder = Action.type(type);
        int i = 0;
        while (i < data.length) {
            String key = (String) data[i++];
            Object value = data[i++];
            actionBuilder.bundle(key, value);
        }
        // 向总线发送消息
        postToBus(actionBuilder.build());
    }

    private boolean isEmpty(String type) {
        return type == null || type.isEmpty();
    }

    // 像总线发送消息
    private void postToBus(final Object event) {
        bus.post(event);
    }
}
